<template>
  <div class="page goods-edit">
    <mt-datetime-picker
      v-if="startPickerVisible"
      ref="startPicker"
      class="date-timer-picker"
      type="date"
      v-model="startDate"
      year-format="{value}年"
      month-format="{value}月"
      date-format="{value}日"
      confirmText="下一步"
      @confirm="endPicker"
      @cancel="cancelPicker"
      :startDate="startDateScope"
      :endDate="endDateScope"
    ></mt-datetime-picker>
    <mt-datetime-picker
      v-if="endPickerVisible"
      ref="endPicker"
      type="date"
      class="date-timer-picker"
      v-model="endDate"
      year-format="{value}年"
      month-format="{value}月"
      date-format="{value}日"
      :startDate="startDateScope2"
      :endDate="endDateScope"
      @confirm="dateChoice"
      @cancel="cancelPicker"
    ></mt-datetime-picker>
    <StoreChoice
      ref="StoreChoice"
      :current="checkeShopList"
      :multipleChoice="true"
      @listenToStoreSelect="getSelectStoreValue"
      :multipleSelectAll="false"
      :hasTotal="false"
      reqUrl="/newapp/shop/getMarketShopSelect.do"
      msg="仅展示已订购小程序的门店，可联系您的销售经理开通更多。"
    />
    <goodsDetails ref="goodsDetails" :detailsParam="detailsData" @saveDetailsData="getDetailsData"></goodsDetails>
    <mt-actionsheet :actions="actionsImg" v-model="chooseImgVisible"></mt-actionsheet>
    <mt-actionsheet :actions="qTypeActions" v-model="qTypeSheetVisible"></mt-actionsheet>
    <mt-actionsheet :actions="qExpActions" v-model="qExpSheetVisible"></mt-actionsheet>
    <div class="scroll-view">
      <customHeader :middleTitle="title" />
      <div class="page-body">
        <ul class="form-style">
          <div class="upload-img">
            <div class="swipe-box" v-show="goodsPic.length">
              <div class="up-btn" @click="chooseImg" v-show="goodsPic.length<10">
                <i class="zhk-xiangji_2"></i>
              </div>
              <i class="zhk-sbylx" @click="delGoodsPic"></i>
              <mt-swipe :auto="0" :show-indicators="true" @change="handleSwipeChange">
                <mt-swipe-item v-for="(i, index) in goodsPic" :key="index">
                  <img :src="repeatImgUrl(i)" @click="replaceImg('',index)" alt />
                </mt-swipe-item>
              </mt-swipe>
            </div>
            <div class="up-btn-box" @click="chooseImg" v-show="!goodsPic.length">
              <div class="up-btn">
                <i class="zhk-xiangji_2"></i>
              </div>
              <span>添加商品图片</span>
            </div>
          </div>
          <li>
            <span>商品名称</span>
            <div>
              <textarea
                v-model.trim="goodsName"
                class="goods-name"
                maxlength="50"
                placeholder="请输入商品名称，最多50个字"
              ></textarea>
            </div>
          </li>
          <li class="column">
            <span>商品列表图</span>
            <div>
              <div
                v-show="!goodsHeadPic"
                class="upload-placeholder"
                @click="chooseImg('goodsHeadPic')"
              >
                <i class="zhk-sczp"></i>
              </div>
              <div class="head-img-box" v-show="goodsHeadPic">
                <img
                  :src="repeatImgUrl(goodsHeadPic)"
                  alt
                  @click="chooseImg('goodsHeadPic')"
                />
                <i class="zhk-sbylx" @click="delHeadPic"></i>
              </div>
            </div>
          </li>
          <li @click="($route.query['type']!=1)&&showAction('qType')">
            <span>电子券类型</span>
            <div :class="{'disabled':$route.query['type']==1}">
              {{qType.name}}
              <i class="zhk-list_rarrow"></i>
            </div>
          </li>
          <li v-show="qType.val==1">
            <span>券面额</span>
            <div :class="{'disabled':$route.query['type']==1}">
              <input
                v-if="$route.query['type']!=1"
                type="number"
                v-model.trim.number="facePrice"
                placeholder="请输入"
              />
              <span v-else>{{facePrice}}</span>
              元
            </div>
          </li>
          <li v-show="qType.val==2">
            <span>原价</span>
            <div>
              <input type="number" v-model.trim.number="originalPrice" placeholder="请输入" />元
            </div>
          </li>
          <li>
            <span>售价</span>
            <div :class="{'disabled':$route.query['type']==1}">
              <input
                v-if="$route.query['type']!=1"
                type="number"
                v-model.trim.number="price"
                placeholder="请输入"
              />
              <span v-else>{{price}}</span>
              元
            </div>
          </li>
          <li>
            <span>发放数量</span>
            <div v-if="!$route.query['type']">
              <div class="num-box">
                <i
                  class="zhk-js"
                  :class="minClass ? 'activeClass' : 'disabledClass' "
                  @click="numberChange('reduce','counter')"
                ></i>
                <input class="buy-num" name type="number" v-model.trim.number="counter" />
                <i
                  class="zhk-zj"
                  :class="addClass ? 'activeClass' : 'disabledClass' "
                  @click="numberChange('add','counter')"
                ></i>
              </div>
            </div>
            <div v-else class="disabled">{{counter}}</div>
          </li>
          <li v-if="$route.query['type']">
            <span>增加发放数量</span>
            <div>
              <div class="num-box">
                <i
                  class="zhk-js"
                  :class="minClass ? 'activeClass' : 'disabledClass' "
                  @click="numberChange('reduce','counter2')"
                ></i>
                <input class="buy-num" name type="number" v-model.trim.number="counter2" />
                <i
                  class="zhk-zj"
                  :class="addClass ? 'activeClass' : 'disabledClass' "
                  @click="numberChange('add','counter2')"
                ></i>
              </div>
            </div>
          </li>
          <li>
            <span>适用门店</span>
            <div @click="showStore" v-if="roleInfo['manyShopFlag']">
              {{storeFormate()}}
              <i class="zhk-list_rarrow"></i>
            </div>
            <div v-else>{{roleInfo['shopName']}}</div>
          </li>
          <li>
            <span>商品详情</span>
            <div @click="linkToGoodsDetails">
              <i class="zhk-list_rarrow"></i>
            </div>
          </li>
          <li @click="showAction('qExp')" v-if="false">
            <span>券有效期</span>
            <div>
              {{qExp.name}}
              <i class="zhk-list_rarrow"></i>
            </div>
          </li>
          <li v-show="qExp.val==1">
            <span></span>
            <div class="exp-day">
              购买后
              <input type="number" v-model.trim.number="validityPeriod" placeholder="请输入" />天内有效
            </div>
          </li>
          <li v-show="qExp.val==2">
            <span></span>
            <div class="exp-date" @click="startPicker">
              <div v-show="effectiveStartTime">{{formateDate(startDate)}} 至 {{formateDate(endDate)}}</div>
              <div v-show="!effectiveStartTime">
                <input type="text" readonly v-model="effectiveStartTime" placeholder="开始时间" />至
                <input type="text" readonly v-model="effectiveEndTime" placeholder="结束时间" />
              </div>
            </div>
          </li>
          <li>
            <span>每人限购份数</span>
            <div>
              <input type="number" v-model.trim="buyLimit" placeholder="不限制" />
            </div>
          </li>
        </ul>
        <ul class="form-style">
          <li class="column">
            <span>购买须知</span>
            <div>
              <div class="remark-box">
                <textarea
                  v-model.trim="buyNotice"
                  class="remark"
                  placeholder="请输入购买须知，最多1024个字"
                  maxlength="1024"
                ></textarea>
                <div class="input-num">{{buyNotice.length}}/1024</div>
              </div>
            </div>
          </li>
        </ul>
      </div>
      <div class="btn-box" v-show="$route.query['type']!=1">
        <div @click="save">保存</div>
        <div class="primary" @click="save('up')">上架出售</div>
      </div>
      <div class="btn-box" v-show="$route.query['type']==1">
        <div class="primary" @click="save">保存</div>
      </div>
    </div>
  </div>
</template>

<script>
import Vue from 'vue';
import customHeader from '../../components/header/header';
import goodsDetails from "./goodsDetails";
import StoreChoice from "../../components/StoreChoice/StoreChoice";
import jsBridge from "../../tools/jsBridge";
import config from "../../base/profile/config.json";
import moment from "moment";
import { Toast, Actionsheet, Swipe, SwipeItem, MessageBox } from 'mint-ui';
Vue.component(Swipe.name, Swipe);
Vue.component(SwipeItem.name, SwipeItem);
export default {
  name: 'goodsEdit',
  data() {
    return {
      startDate: new Date(),
      endDate: new Date(moment().add(1, "year").valueOf()),
      startPickerVisible: false,
      endPickerVisible: false,
      startDateScope: new Date(), //可选开始日期范围
      startDateScope2: new Date(moment().add(1, "year").valueOf()), //可选结束日期范围
      endDateScope: new Date(moment().add(1, "year").valueOf()),

      goodsName: "",
      originalPrice: null,
      facePrice: null,
      price: null,
      validityPeriod: null,
      effectiveStartTime: null,
      effectiveEndTime: null,
      buyLimit: null,
      buyNotice: "",
      title: "新增商品",
      loadding: false,
      qTypeSheetVisible: false,
      qExpSheetVisible: false,
      chooseImgVisible: false,
      qTypeActions: [{ name: "代金券", val: 1, method: this.handleQTypeActionSelect }, { name: "套餐券", val: 2, method: this.handleQTypeActionSelect }],
      qExpActions: [{ name: "购买若干天内有效", val: 1, method: this.handleQExpActionSelect }, { name: "指定日期内有效", val: 2, method: this.handleQExpActionSelect }],
      qType: { name: "请选择", val: "", },
      qExp: { name: "请选择", val: "", },
      minClass: false,
      addClass: true,
      counter: 1,
      counter2: 0,
      maxCount: 999999,
      checkeShopList: [],
      actionsImg: [],
      goodsPic: [],
      goodsHeadPic: "",
      goodsPicIndex: 0,
      detailsParam: null,
      detailsData: [],
      loadding: false,
      editData: {},
      roleInfo: {}
    };
  },

  methods: {
    //日期选择展开
    startPicker() {
      this.startPickerVisible = true;
      this.endPickerVisible = true;
      this.$nextTick(() => {
        this.$refs.startPicker.open();
      });
    },
    //结束日期展开
    endPicker(e) {
      this.startDateScope2 = e;

      this.$nextTick(() => {
        this.$refs.endPicker.open();
      });
    },
    //结束日期选择
    dateChoice(e) {
      this.startPickerVisible = false;
      this.endPickerVisible = false;
      this.effectiveStartTime = this.startDate;
      this.effectiveEndTime = this.endDate;
    },
    //点取消关闭日期组件
    cancelPicker() {
      this.startPickerVisible = false;
      this.endPickerVisible = false;
    },
    formateDate(date) {
      if (typeof date == "object") {
        return moment(date).format("YYYY-MM-DD");
      } else {
        return date;
      }
    },
    getDetailsData(v) {
      this.detailsData = v;
    },
    delGoodsPic() {
       MessageBox({
          title: '提示',
          message: '确认要删除该张图片吗？',
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          showCancelButton: true
        }).then((action) => {
          if (action == 'confirm') {
            this.goodsPic.splice(this.goodsPicIndex, 1);
          }
        })
     
    },
    delHeadPic() {
      this.goodsHeadPic = "";
    },
    handleSwipeChange(index) {
      this.goodsPicIndex = index;
    },
    showStore() {
      this.$refs.StoreChoice.popupShow();
    },
    linkToGoodsDetails() {
      this.$refs.goodsDetails.popupShow();
    },
    storeFormate() {
      let v = "请选择";
      if (!this.checkeShopList) {

      }
      else if (this.checkeShopList.length === 1) {
        v = this.checkeShopList[0].selectName;
      } else if (this.checkeShopList.length > 1) {
        v = "已选" + this.checkeShopList.length + "家门店";
      }
      return v;
    },
    getSelectStoreValue(value, storeName) {
      this.checkeShopList = value;
    },
    replaceImg(field, index){
       MessageBox({
          title: '提示',
          message: '确认要替换该张图片吗？',
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          showCancelButton: true
        }).then((action) => {
          if (action == 'confirm') {
            this.chooseImg(field, index);
          }
        })
    },
    //上传
    chooseImg(field, index) {
      const _this = this;
      const crop=field == "goodsHeadPic"?{ heightRatio: 600, widthRatio: 600 }:{ heightRatio:560, widthRatio:750};
      _this.actionsImg = [
        {
          name: "拍照",
          method: function () {
            jsBridge.selectPicture(
              { options: "拍照", crop: crop },
              function (result) {
                _this.doUploadPic(result, field, index);
              },
              function (result) {
              }
            );
          }
        },
        {
          name: "选择图片",
          method: function () {
            jsBridge.selectPicture(
              {
                options: "选择图片",
                crop: crop
              },
              function (result) {
                _this.doUploadPic(result, field, index);
              },
              function (result) {
 
              }
            );
          }
        }
      ];

      this.chooseImgVisible = true;
      return false;
    },
    doUploadPic(result, field, index) {
      const url = window.APP.serverUrl + "/app/img/uploadShopImg.do";
      jsBridge.uploadPic(
        {
          url: url,
          file: result.resultObject,
          data: {},
          crop: {},
          compress: { sizeLimit: "2", unit: "M" }
        },
        (result) => {
          //以下为正常的业务逻辑
          if (result && result.success) {
            const uploadResult = result.resultObject;
            if (uploadResult) {
              if (field == "goodsHeadPic") {
                this.goodsHeadPic = uploadResult.imageUrl;
              } else {//组图
                if (index != undefined) {//替换
                  this.goodsPic[index] = uploadResult.imageUrl;
                } else {//追加
                  this.goodsPic.push(uploadResult.imageUrl);
                }
              }
              return;
            }
          }
          const msg = result.msg || "上传失败";
          Toast(msg);
        },
        (result) => {

        }
      );
    },
    repeatImgUrl(url, resize) {
      if (resize) {
        return CommonUtil.imgUrlFormate(url, config.previewUrlPrefix) + "?" + CommonUtil.imgUrlResize('m_fill', '206', '320');
      }
      return CommonUtil.imgUrlFormate(url, config.previewUrlPrefix)
    },
    numberChange(type, field) {
      if (type == "reduce" && this[field] > 1) {
        this[field] = parseInt(this[field]) - 1;
      }
      if (type == "add" && this[field] < this.maxCount) {
        this[field] = parseInt(this[field]) + 1;
      }
    },
    handleQTypeActionSelect(e) {
      this.qType = e;
    },
    handleQExpActionSelect(e) {
      this.qExp = e;
    },
    showAction(ref) {
      this[ref + 'SheetVisible'] = true;
    },
    handleStatusChange(v) {
      this.currStatus = v.value;
    },
    getDetails() {
      const url = "/newapp/goods/service/queryGoodsDetail.do?goodsId=" + this.$route.query.id;
      this.ajax({
        url: url,
        type: "get",
        controlLoading: true
      })
        .then(res => {
          if (res.success) {
            const data = res.resultObject;
            const goods = res.resultObject.goodsSalesSkuModel;
            this.editData = data;
            this.goodsPic = goods.imageList;
            this.goodsName = data.goodsName;
            this.goodsHeadPic = goods.cover;
            this.qTypeActions.map((item) => {
              if (item.val == data.ticketType) {
                this.qType = { name: item.name, val: item.val };
              }
            });
            this.originalPrice = goods.originalPrice;
            this.facePrice = goods.facePrice;
            this.price = goods.price;
            this.counter = data.inventory;
            this.counter2 = data.addInventory ? data.addInventory : 0;
            this.checkeShopList = data.shopList.map((item) => { return { selectName: item.shopName, selectKey: item.shopId } });
            this.detailsData = JSON.parse(goods.goodsDetails);
            // this.qExpActions.map((item) => {
            //   if (item.val == goods.effectiveType) {
            //     this.qExp = { name: item.name, val: item.val };
            //   }
            // });
            this.validityPeriod = goods.validityPeriod;
            if (goods['effectiveStartTime']) {
              this.effectiveStartTime = new Date(goods.effectiveStartTime);
              this.effectiveEndTime = new Date(goods.effectiveEndTime);
            }
            this.buyLimit = goods.buyLimit == -1 ? "" : goods.buyLimit;
            this.buyNotice = goods.buyNotice;
          } else {
            Toast(res.msg);
          }
        })
        .catch((err) => {

        });
    },
    linkToAdd() {
      this.$router.push({ path: '/goodsManage/eidt', query: { type: 0 } });
    },
    save(type) {
      if (!this.formValidate()) {
        return;
      }
      if (this.$route.query["type"]) {
        MessageBox({
          title: '提示',
          message: '本次提交将改变在售商品信息展示，为保障商家和消费者共同权益，请谨慎修改。',
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          showCancelButton: true
        }).then((action) => {
          if (action == 'confirm') {
            this.submitAjax(type);
          }
        })
      } else {
        this.submitAjax(type);
      }
    },
    priceReg(v) {
      return /((^[1-9]\d*)|^0)(\.\d{0,2}){0,1}$/.test(v);
    },
    formValidate() {
      if (!this.goodsPic.length) {
        Toast("请上传商品图片");
        return false;
      }
      if (!this.goodsName) {
        Toast("请填写商品标题");
        return false;
      }
      if (this.goodsName.length > 50) {
        Toast("商品标题不能超出50个字");
        return false;
      }
      if (!this.goodsHeadPic) {
        Toast("请上传商品列表图");
        return false;
      }
      if (!this.qType.val) {
        Toast("请选择电子券类型");
        return false;
      }
      if (this.qType.val == 1 && !this.facePrice) {
        Toast("请输入券面额");
        return false;
      }
      if (this.qType.val == 1 && this.priceReg(this.facePrice) && (this.facePrice < 0.01 || this.facePrice > 99999.99)) {
        Toast("请输入正确的券面额");
        return false;
      }
      if (this.qType.val == 2 && !this.originalPrice) {
        Toast("请输入原价");
        return false;
      }
      if (this.qType.val == 2 && this.priceReg(this.originalPrice) && (this.originalPrice < 0.01 || this.originalPrice > 99999.99)) {
        Toast("请输入正确的原价");
        return false;
      }
      if (!this.price) {
        Toast("请输入售价");
        return false;
      }
      if (this.priceReg(this.originalPrice) && (this.price < 0.01 || this.price > 99999.99)) {
        Toast("请输入正确的售价");
        return false;
      }
      if ((this.qType.val == 1 && this.price > this.facePrice) || (this.qType.val == 2 && this.price > this.originalPrice)) {
        Toast("售价不能大于原价或券面额");
        return false;
      }
      if (!this.counter) {
        Toast("请设置发放数量");
        return false;
      }
      if (!this.checkeShopList.length) {
        Toast("请选择适用门店");
        return false;
      }
      // if (!this.qExp.val) {
      //   Toast("请设置券有效期");
      //   return false;
      // }
      // if (this.qExp.val == 1 && !this.validityPeriod) {
      //   Toast("请设置券有效期");
      //   return false;
      // }
      // if (this.qExp.val == 2 && ((!this.effectiveStartTime) || (!this.effectiveEndTime))) {
      //   Toast("请设置券有效期");
      //   return false;
      // }

      if (this.buyLimit && (Number(this.buyLimit < 1) || Number(this.buyLimit) > this.counter + this.counter2)) {
        Toast("请输入正确的限购份数");
        return false;
      }

      return true;
    },
    submitAjax(type) {
      if (this.loadding) {
        return;
      }
      let url = "/newapp/goods/service/addGoods.do";
      if (this.$route.query["type"]) {
        url = "/newapp/goods/service/editGoods.do";
      }
      const shop = this.checkeShopList.map((item) => {
        return item.selectKey;
      });
      //const shop = ["20190925210559393223"];
      const buyLimit = this.buyLimit ? Number(this.buyLimit) : -1;
      const params = {
        images: this.goodsPic,
        goodsName: this.goodsName,
        cover: this.goodsHeadPic,
        ticketType: this.qType.val,
        // originalPrice: this.originalPrice,
        // facePrice: this.facePrice,
        price: this.price,
        inventory: this.counter,
        shopIdList: shop,
        goodsDetails: JSON.stringify(this.detailsData),
        effectiveTime: {
          effectiveType: 1,//this.qExp.val,
          validityPeriod: -1,   //写死不限制
          // validityPeriod: this.validityPeriod,
          // effectiveStartTime: this.effectiveStartTime,
          // effectiveEndTime: this.effectiveEndTime
        },
        buyLimit: buyLimit,
        buyNotice: this.buyNotice
      }
      if (this.qType.val == 2) {
        params["originalPrice"] = this.originalPrice;
      } else if (this.qType.val == 1) {
        params["facePrice"] = this.facePrice;
      }
      // if (this.qExp.val == 2) {
      //   params["effectiveTime"]["effectiveStartTime"] = this.effectiveStartTime.valueOf();
      //   params["effectiveTime"]["effectiveEndTime"] = this.effectiveEndTime.valueOf();
      // } else if (this.qExp.val == 1) {
      //   params["effectiveTime"]["validityPeriod"] = this.validityPeriod;
      // }
      if (this.$route.query["type"]) {
        params["goodsId"] = this.$route.query.id;
        params["addInventory"] = this.counter2;
        params["status"] = this.editData.status;
      }
      this.loadding = true;
      this.ajax({
        url: url,
        type: "post",
        data: params,
        controlLoading: true
      })
        .then(res => {
          this.loadding = false;
          if (res.success) {
            if (type == "up" && res.resultObject) {
              this.statusChange(res.resultObject, 1);//上架
            } else {
              Toast("操作成功");
              this.$router.back();
            }

          } else {
            Toast(res.msg);
          }
        });
    },
    //上架
    statusChange(id, status) {
      if (this.loadding) {
        return;
      }
      let params = { goodsId: id, status: status, operatorId: "" };
      this.loadding = true;
      this.ajax({
        url: "/newapp/goods/service/manageGoodsStatus.do",
        type: "post",
        data: params,
        controlLoading: true
      })
        .then(res => {
          this.loadding = false;
          if (res.success && res.resultObject) {
            Toast("操作成功");
            this.$router.back();
          } else {
            Toast(res.msg);
          }
        })
    },

  },
  watch: {
    counter(newValue, oldValue) {
      if (newValue <= 1) {
        if (newValue < 1) {
          this.counter = 1;
        }
        this.minClass = false;
        this.addClass = true;
      } else if (newValue > 1 && newValue < this.maxCount) {
        this.minClass = true;
        this.addClass = true;
      } else {
        if (newValue > this.maxCount) {
          this.counter = this.maxCount;
          Toast("数量不能超过"+this.maxCount);
        }
        this.minClass = true;
        this.addClass = false;
      }
    },
    counter2(newValue, oldValue) {
      if (newValue <= 0) {
        if (newValue < 0) {
          this.counter2 = 0;
        }
        this.minClass = false;
        this.addClass = true;
      } else if (newValue > -1 && newValue + this.counter < this.maxCount) {
        this.minClass = true;
        this.addClass = true;
      } else {
        if (newValue + this.counter > this.maxCount) {
          this.counter2 = this.maxCount-this.counter;
           Toast("数量不能超过"+(this.maxCount-this.counter));
        }
        this.minClass = true;
        this.addClass = false;
      }
    }
  },
  components: {
    customHeader,
    StoreChoice,
    goodsDetails
  },
  created() {
    const params = this.$route.query;
    if (params['type'] == 1) {
      this.title = "编辑商品";
      this.getDetails();
    }
    CommonUtil.getUserInfo().then(userInfo => {
      this.roleInfo = userInfo;
      if (!this.roleInfo.manyShopFlag) {
        this.checkeShopList = [
          {
            selectName: this.roleInfo.shopName,
            selectKey: this.roleInfo.yzShopId
          }
        ];
      }
    });
  },
};
</script>
<style lang='scss' scoped>
@import "goodsManage";
</style>
<style lang='scss'>
.mint-swipe-indicator {
  background: #fff !important;
  opacity: 1 !important;
}
</style>
